package com.pvdnc.worldmagisk.shell.server;

import android.system.Os;
import android.util.Log;

import com.pvdnc.worldmagisk.shell.PacketDecoder;
import com.pvdnc.worldmagisk.shell.PacketEncoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;

public class ShellServer {
    private static final String TAG=ShellServer.class.getSimpleName();

    private int mPort;
    public ShellServer(int port){
        mPort=port;
    }

    private ServerBootstrap getDefault(){
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .group(boosGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {
                        ChannelPipeline pipeline=ch.pipeline();
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 4, 4));
                        ch.pipeline().addLast(new PacketDecoder());
                        ch.pipeline().addLast(new CommandRequestHandler());
                        ch.pipeline().addLast(new PacketEncoder());
                    }
                });
        return serverBootstrap;
    }

    public void doBind(){
        getDefault().bind(mPort).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Log.d(TAG,"server bind");
            }
        });
    }

    public static final int DEFAULT_PORT=9725;

    public static void main(String[] args){
        Log.d(TAG,"shell server is on pid:"+ Os.getpid()+" uid:"+Os.getuid());
        System.out.println("shell server is on pid:"+ Os.getpid()+" uid:"+Os.getuid());
        int port=DEFAULT_PORT;
        Log.d(TAG,"port:"+port);
        new ShellServer(port).doBind();
        while (true){

        }
    }
}
